package com.proton.carepatchtemp.fragment;


import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.apkfuns.logutils.LogUtils;
import com.proton.carepatchtemp.R;
import com.proton.carepatchtemp.adapter.RealTimeTestAdapter;
import com.proton.carepatchtemp.application.VCare;
import com.proton.carepatchtemp.base.BaseFragment;
import com.proton.carepatchtemp.constant.Codes;
import com.proton.carepatchtemp.constant.XTypes;
import com.proton.carepatchtemp.database.RealData;
import com.proton.carepatchtemp.database.TestManager;
import com.proton.carepatchtemp.database.XmppMsg;
import com.proton.carepatchtemp.database.table.Device;
import com.proton.carepatchtemp.database.table.ShareHistory;
import com.proton.carepatchtemp.utils.TastyUtils;
import com.proton.carepatchtemp.utils.eventbus.MainEvent;
import com.proton.carepatchtemp.utils.net.XMPPCenter;
import com.sdsmdg.tastytoast.TastyToast;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import cn.pedant.SweetAlert.SweetAlertDialog;
import cn.pedant.SweetAlert.Type;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link RealTimeTestFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class RealTimeTestFragment extends BaseFragment {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    public ArrayMap<String, RealData> mList = new ArrayMap<>();
    public List<RealTimeItemFragment> mFragments = new ArrayList<>();
    public List<RealTimeShareFragment> mSharedFragments = new ArrayList<>();
    private ViewPager mVpRealTimeList;
    //  屏幕当前是否显示新设备dialog
    private boolean isShowNewS = false;
    //  已经接收的分享ReportId集合
    private List<Long> recShare = new ArrayList<>();
    //  主动销毁的分享界面
    private List<Long> deleteShare = new ArrayList<>();
    private RealTimeTestAdapter mAdapter;
    private ProgressDialog mProgressDialog;
    private RealData mTempInfo;
    private LinearLayout mGuideLlPoint;

    //实例化原点View
    private List<ImageView> ivPointArray;

    public RealTimeTestFragment() {
        mTempInfo = new RealData();
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment RealTimeTestFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static RealTimeTestFragment newInstance(String param1, String param2) {
        RealTimeTestFragment fragment = new RealTimeTestFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void dealEvent(MainEvent event) {
        switch (event.getId()) {
            //来自分享设备的数据
            case Codes.XMPP_MSG_DATA:
                XmppMsg tempMsg = (XmppMsg) event.getObj();
//                LogUtils.e(event);
                if (deleteShare.contains(tempMsg.getReportId())) {
                    return;
                }
                switch (tempMsg.getDisplayStatus()) {
                    case XTypes.STATUS_INFO:
                        //  防止因为XMPP信息延迟导致重复接收数据
                        if (mSharedFragments.size() > 0) {
                            for (RealTimeShareFragment rsf :
                                    mSharedFragments) {
                                if (rsf.reportID.equalsIgnoreCase(event.getKey())) {
                                    rsf.addData(tempMsg, Long.parseLong(event.getMsg()));
                                    break;
                                }
                            }
                        }

                        if (recShare.contains(tempMsg.getReportId())) {
                            break;
                        }

                        if (isShowNewS) {
                            break;
                        }
                        isShowNewS = true;
                        SweetAlertDialog mydialog = new SweetAlertDialog(getContext(), Type.NORMAL_TYPE);
                        mydialog.setCancelable(false);
                        mydialog.setTitleText(getString(R.string.string_tips));
                        mydialog.setContentText(getString(R.string.string_come_from) + tempMsg.getDisplayName() + getString(R.string.string_device_share_accept));
                        mydialog.showCancelButton(true);
                        mydialog.setConfirmText(getString(R.string.string_accept));
                        mydialog.setCancelText(getString(R.string.string_cancel));
                        mydialog.setCancelClickListener(sweetAlertDialog -> {
                            deleteShare.add(tempMsg.getReportId());
                            tempMsg.setUid(VCare.get().getUid());
                            tempMsg.setDisplayStatus(XTypes.STATUS_REFUSEREC);
                            XMPPCenter.sendMsg(tempMsg, tempMsg.getUid());
                            isShowNewS = false;
                            mydialog.dismiss();
                        });
                        mydialog.setConfirmClickListener(sweetAlertDialog -> {
                            tempMsg.setDisplayStatus(XTypes.STATUS_CANSEND);
                            XMPPCenter.sendMsg(tempMsg, tempMsg.getUid());
                            if (RealTimeTestFragment.this.isHidden()) {
                                EventBus.getDefault().post(new MainEvent(Codes.XMPP_SHOW_TEST));
                            }
                            recShare.add(tempMsg.getReportId());
                            addShareFrag(tempMsg);
                            isShowNewS = false;
                            mydialog.dismiss();
                        });
                        mydialog.show();

                        break;

                    case XTypes.STATUS_STOP_TEST:
                        LogUtils.e(tempMsg);
                        deleteShareFrag(tempMsg);
                        deleteShare.add(tempMsg.getReportId());
                        AlertDialog.Builder ADBuilder = new AlertDialog.Builder(getActivity());
                        ADBuilder.setTitle(getString(R.string.string_stop_measure));
                        ADBuilder.setMessage(R.string.string_measure_end);
                        ADBuilder.setNegativeButton(getString(R.string.string_confirm), (dialog, which) -> {

                        });
                        AlertDialog dialog = ADBuilder.create();
                        dialog.setCancelable(false);
                        //在dialog  show方法之前添加如下代码，表示该dialog是一个系统的dialog**
                        dialog.getWindow().setType((WindowManager.LayoutParams.TYPE_TOAST));
                        dialog.show();
                        break;
                    case XTypes.STATUS_UNSHARE:
                        LogUtils.d(tempMsg);
                        deleteShareFrag(tempMsg);
                        AlertDialog.Builder ADBuilder1 = new AlertDialog.Builder(getActivity());
                        ADBuilder1.setTitle(R.string.string_cancel_share);
                        ADBuilder1.setMessage(tempMsg.getDisplayName() + " " + getString(R.string.string_cancel_share_device));
                        ADBuilder1.setNegativeButton(getString(R.string.string_confirm), (dialog1, which) -> {

                        });
                        AlertDialog dialog1 = ADBuilder1.create();
                        dialog1.setCancelable(false);
                        //在dialog  show方法之前添加如下代码，表示该dialog是一个系统的dialog**
                        dialog1.getWindow().setType((WindowManager.LayoutParams.TYPE_TOAST));
                        dialog1.show();
                        break;
                    case XTypes.STATUS_DISCONNECTED:
                        for (RealTimeShareFragment rsf :
                                mSharedFragments) {
                            if (rsf.reportID.equalsIgnoreCase(event.getKey())) {
                                int postion = mFragments.indexOf(rsf);
                                mVpRealTimeList.setCurrentItem(postion);
                                return;
                            }
                        }
                        AlertDialog.Builder ADBuilder2 = new AlertDialog.Builder(getActivity());
                        ADBuilder2.setTitle(R.string.string_device_disconnect);
                        ADBuilder2.setMessage(R.string.string_device_disconnect_2);
                        ADBuilder2.setNegativeButton(getString(R.string.string_confirm), (dialog2, which) -> {

                        });
                        AlertDialog dialog2 = ADBuilder2.create();
                        dialog2.setCancelable(false);
                        //在dialog  show方法之前添加如下代码，表示该dialog是一个系统的dialog**
                        dialog2.getWindow().setType((WindowManager.LayoutParams.TYPE_TOAST));
                        dialog2.show();
                        break;
                    case XTypes.STATUS_DELETEPAGER:
                        deleteShare.add(tempMsg.getReportId());
                        deleteShareFrag(tempMsg);
                        break;
                    case XTypes.STATIS_DELETE_NODATA:
                        if (null == getActivity()) {
                            return;
                        }
                        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                        builder.setTitle(R.string.string_share_device_exception);
                        builder.setMessage(R.string.string_connect_timeout);
                        builder.setCancelable(false);
                        builder.setNegativeButton(getString(R.string.string_confirm), (dialog3, which) -> {

                        });
                        AlertDialog mMdialog = builder.create();
                        if (mMdialog.isShowing()) {

                        } else {
                            mMdialog.show();
                        }
                        deleteShareFrag(tempMsg);
                        break;
                    case XTypes.STATUS_REFUSEREC:
                        //拒绝接收
                        LogUtils.e(tempMsg);
                        for (RealTimeItemFragment r :
                                mFragments) {
                            if (TestManager.getReportID(r.tag) == tempMsg.getReportId()) {
                                for (ShareHistory.SharelistBean sb :
                                        TestManager.getShareList(r.tag)) {
                                    LogUtils.e(sb);
                                    if (sb.getUid() == tempMsg.getUid()) {
                                        sb.setCanSend(false);
                                    }
                                }
                            }
                        }
                        break;
                    case XTypes.STATUS_STOPREC:
                        for (RealTimeItemFragment r :
                                mFragments) {
                            if (TestManager.getReportID(r.tag) == tempMsg.getReportId()) {
                                for (ShareHistory.SharelistBean sb :
                                        TestManager.getShareList(r.tag)) {
                                    LogUtils.e(sb);
                                    if (sb.getUid() == tempMsg.getUid()) {
                                        sb.setCanSend(false);
                                    }
                                }
                            }
                        }
                        break;
                    case XTypes.STATUS_CANSEND:
//                        for (RealTimeItemFragment rsf :
//                                mFragments) {
//                            if (rsf.reportId.equalsIgnoreCase(tempMsg.getReportId() + "")) {
//                                int postion = mFragments.indexOf(rsf);
//                                mFragments.remove(rsf);
//                                mSharedFragments.remove(rsf);
//                                mAdapter.getFragmentManager().beginTransaction().remove(rsf).commitAllowingStateLoss();
//                                mVpRealTimeList.setCurrentItem(mFragments.size() - 1, true);
//                                //      删除导航圆点
//                                mGuideLlPoint.removeView(ivPointArray.get(postion));
//                                ivPointArray.remove(postion);
//                                if (mFragments.size() > 0) {
//                                    ivPointArray.get(mFragments.size() - 1).setImageResource(R.mipmap.guide_pointon);
//                                }
//                                return;
//                            }
//                        }
                        break;
                    default:
                        break;
                }
                break;
            //  添加一个新的测试设备
            case Codes.BT_ADD_DEVICE_CONNECT:
//                mSrcvRealtimeList.setVisibility(View.VISIBLE);
                Device tempDevice = (Device) event.getObj();
                if (mList.containsKey(tempDevice.getBtaddress())) {
                    TestManager.get(tempDevice.getBtaddress()).isTesting = true;
                    break;
                }
                RealData tempInfo = new RealData();
                tempInfo.setDevice(tempDevice);
                tempInfo.setProfile(mTempInfo.getProfile());
                tempInfo.isTesting = true;
                mList.put(tempDevice.getBtaddress(), tempInfo);
                //  此处必须new一个新的，因为mTempInfo只new了一次，内容是持续改变的，仅仅只是作为一个缓冲，会导致fragmentItem中的混乱

                for (RealTimeItemFragment frag :
                        mFragments) {
                    if (frag.tag.equalsIgnoreCase(tempInfo.getDevice().getBtaddress())) {
                        return;
                    }
                }

                //添加导航小圆点
                ImageView imageView = new ImageView(getActivity());
                imageView.setImageResource(R.mipmap.guide_pointon);
                imageView.setLayoutParams(new ViewGroup.LayoutParams(20, 20));
                mGuideLlPoint.addView(imageView);
                ivPointArray.add(imageView);
                // 添加基本的测试信息到容器当中
                TestManager.put(tempInfo.getDevice().getBtaddress(), tempInfo);

                mFragments.add(RealTimeItemFragment.newInstance(tempInfo.getDevice().getBtaddress(), tempInfo));
                LogUtils.e(mList);
                mAdapter.notifyDataSetChanged();
                mVpRealTimeList.setCurrentItem(mFragments.size() - 1, true);

                LogUtils.d(tempDevice);
                break;

            case Codes.TEST_DELTE_PAGER:
                if (!TextUtils.isEmpty(event.getKey())) {
                    String key = event.getKey();
                    for (RealTimeItemFragment frag : mFragments
                            ) {
                        if (key.equalsIgnoreCase(frag.tag)) {
                            mProgressDialog.dismiss();
                            int postion = mFragments.indexOf(frag);
                            if (1 == frag.isDelete) {
                                break;
                            }
                            if (0 == frag.isDelete) {
                                break;
                            }

                            mFragments.remove(frag);
                            mList.remove(key);
                            mAdapter.getFragmentManager().beginTransaction().remove(frag).commitAllowingStateLoss();
                            mAdapter.notifyDataSetChanged();
                            mVpRealTimeList.setCurrentItem(mFragments.size() - 1, true);
                            //      删除导航圆点
                            mGuideLlPoint.removeView(ivPointArray.get(postion));
                            ivPointArray.remove(postion);
                            TestManager.remove(key);
                            if (mFragments.size() > 0) {
                                ivPointArray.get(mFragments.size() - 1).setImageResource(R.mipmap.guide_pointon);
                            } else {
                                EventBus.getDefault().post(new MainEvent(Codes.TEST_SHOW_SEARCH));
                            }

                            LogUtils.e(mFragments);
                            break;
                        }
                    }
                    if (mProgressDialog.isShowing()) {
                        mProgressDialog.dismiss();
                        TastyUtils.makeTextShort(R.string.disconnect_device_failed, TastyToast.ERROR);
                    }
                } else {
                    mProgressDialog.dismiss();
                    TastyUtils.makeTextShort(R.string.disconnect_device_failed, TastyToast.ERROR);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mProgressDialog = new ProgressDialog(getActivity());
        mAdapter = new RealTimeTestAdapter(getChildFragmentManager(), mFragments);
        ivPointArray = new ArrayList<>();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_real_time_test, container, false);
        initView(view);
        setListener();
        mVpRealTimeList.setOffscreenPageLimit(7);
        mVpRealTimeList.setAdapter(mAdapter);
        mVpRealTimeList.setPageTransformer(true, new ZoomOutPagerTranseFormer());

        return view;
    }

    private void setListener() {
        mVpRealTimeList.addOnPageChangeListener(new MyViewPagerChangeListener());
    }

    @Override
    public void onEventMainThread(MainEvent event) {
        dealOnEvent(event);
    }

    private void initView(View view) {
        mVpRealTimeList = view.findViewById(R.id.vp_real_time_list);
        mGuideLlPoint = view.findViewById(R.id.guide_ll_point);
    }

    private void addShareFrag(XmppMsg xmppMsg) {
        try {
            //添加导航小圆点
            if (xmppMsg == null) return;
            ImageView imageView = new ImageView(getActivity());
            imageView.setImageResource(R.mipmap.guide_pointon);
            imageView.setLayoutParams(new ViewGroup.LayoutParams(20, 20));
            mGuideLlPoint.addView(imageView);
            ivPointArray.add(imageView);

            RealTimeShareFragment realTimeShareFragment = RealTimeShareFragment.newInstance(xmppMsg.getReportId() + "", xmppMsg, null);
            mSharedFragments.add(realTimeShareFragment);
            mFragments.add(realTimeShareFragment);

            mAdapter.notifyDataSetChanged();
            mVpRealTimeList.setCurrentItem(mFragments.size() - 1, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void deleteShareFrag(XmppMsg xmppMsg) {
        recShare.remove(xmppMsg.getReportId());
        for (RealTimeShareFragment rsf :
                mSharedFragments) {
            if (rsf.reportID.equalsIgnoreCase(xmppMsg.getReportId() + "")) {
                int postion = mFragments.indexOf(rsf);
                mFragments.remove(rsf);
                mSharedFragments.remove(rsf);
                mAdapter.getFragmentManager().beginTransaction().remove(rsf).commitAllowingStateLoss();
                mAdapter.notifyDataSetChanged();
                LogUtils.d("remove a share fragment");
                mVpRealTimeList.setCurrentItem(mFragments.size() - 1, true);
                //      删除导航圆点
                mGuideLlPoint.removeView(ivPointArray.get(postion));
                ivPointArray.remove(postion);
                if (mFragments.size() > 0) {
                    ivPointArray.get(mFragments.size() - 1).setImageResource(R.mipmap.guide_pointon);
                } else {
                    //卡片全关清除所有测试信息
                    TestManager.container.clear();
                    EventBus.getDefault().post(new MainEvent(Codes.XMPP_SHOW_SERACH));
                }
                return;
            }
        }
    }

    public RealData getTempInfo() {
        return mTempInfo;
    }

    public void setTempInfo(RealData tempInfo) {
        mTempInfo = tempInfo;
    }

    private class MyViewPagerChangeListener implements ViewPager.OnPageChangeListener {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            //循环设置当前页的标记图
            int length = mFragments.size();
            for (int i = 0; i < length; i++) {
                ivPointArray.get(position).setImageResource(R.mipmap.guide_pointon);
                if (position != i) {
                    ivPointArray.get(i).setImageResource(R.mipmap.guide_pointoff);
                }
            }
//            currentInfo = mFragments.get(position).getRealTimeInfo();
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }
}
